var app = getApp()
var car = require('../../template/car/breakfastcar.js')
var category = require('../../template/category/breadcategory.js')
var {parseDate, formatDate, getNodeRef} = require('../../utils/util')
var allBread, tabsTop = 0
var weekNames = ['日', '一', '二', '三', '四', '五', '六']

Page({
  data: {
    topNeedShow: true,
    dateTabFixed: false,
    isSloganShow: false,
    scrolltop: 0,
    breadType: '1',
    idflag: '',
    address: null,
    showOverlay: false,
    breadLoaded: false,
    stationId: '',
    storeId: '',
    curDate: null,
    breadlist: [],
    dateList: []
  },

  onLoad: function () {
    app.hideLoading()
    getNodeRef('#dateTabs').then(res => tabsTop = res.top - 52)
    this.idFlag = app.globalData.idFlag || ''
    this.initBanner()
    car.init(this)
  },

  onShow: function () {
    this.lastAddress = this.data.address
    app.ready(() => {
      if (app.globalData.address == null) {
        app.showAddressModal()
      } else {
        this.handleReady()
      }
    })
    app.error(err => {
      this.dealEmpty()
      app.toast.error(err)
    })
  },

  handleReady: function () {
    this.setData({
      address: app.globalData.address
    })

    let gAddress = app.globalData.address
    let address = this.lastAddress

    if (address && (gAddress.ID !== address.ID || gAddress.ADDRESS !== address.ADDRESS)) {
      app.globalData.needClearBreadCar = '1'
      this.setData({
        breadLoaded: false
      })
    }

    this.loadData()

    if (this.idFlag) {
      this.setData({
        idflag: this.idFlag
      })
      app.globalData.idFlag = null
    }

    if (app.globalData.needClearBreadCar === '1') {
      app.globalData.needClearBreadCar = null
      car.init(this)
    }
  },

  onShareAppMessage: function () {

  },
  changeDate: function (e) {
    let index = e.currentTarget.dataset.index
    let dateList = this.data.dateList.map((item, i) => ({...item, selected: i === index}))
    let curDate = dateList[index].date

    if (this.data.goodslist.length > 0) {
      app.confirm('切换会清空购物车，是否继续?', '是', '否').then(confirm => {
        if (confirm) {
          this.setData({
            dateList: dateList
          })
          this.loadBreadList(curDate)
          car.init(this)
        }
      })
    } else {
      this.setData({
        breadLoaded: false,
        dateList: dateList,
        scrolltop: 0
      })
      this.loadBreadList(curDate)
    }
  },
  dealEmpty: function () {
    this.hideLoading()
    this.setData({
      breadlist: [],
      breadLoaded: true
    })
    app.confirm('当前地区没有商品可销售，是否去修改地址?', '是', '否').then(confirm => {
      if (confirm) {
        wx.navigateTo({
          url: '/pages/my/address/address?type=select'
        })
      }
    })
  },
  loadAvailableDates: function () {
    let url = `/yuanmai_we/breakfast/delivery/date/get/${this.data.address.CITYID}`
    return app.get(url).then(res => {
      let dateList = res.map((item, i) => {
        let date = parseDate(item.date)
        return {
          week: weekNames[date.getDay()],
          shortDate: formatDate(date, 'MM-dd'),
          date: formatDate(date, 'yyyyMMdd'),
          selected: i === 0
        }
      })
      this.setData({
        dateList: dateList
      })
      return dateList
    })
  },
  getProductTypes: function () {
    return app.get('/yuanmai_we/product/productType').then(res => {
      this.setData({
        productType: res[0].ID
      })
      return res
    })
  },
  loadData: function () {
    Promise.all([
      this.loadAvailableDates(),
      this.getProductTypes()
    ]).then(values => {
      let dateList = values[0]
      if (dateList.length > 0) {
        this.loadBreadList(dateList[0].date)
      } else {
        this.dealEmpty()
      }
    })
  },
  loadBreadList: function (date) {
    var pdtype = this.data.productType
    var city = this.data.address.CITYID
    var url = `/yuanmai_we/breakfast/products/get/${city}/${pdtype}/${date}`

    var property = {
      location: this.data.address.LOCATION,
      hasAddress: !!this.data.address.ADDRESS,
      sortType: "default",
      ORDERSTARTDAY: 'BREAKFAST',
      deliveryType: 'breakfast',
      MENUTYPE: "BREAKFAST"
    }

    var params = {
      __zaofans: true
    }

    this.data.curDate = date
    params.datas = JSON.stringify(property)
    app.request(url, params).then(
      this.breadListCallBack.bind(this),
      err => this.dealEmpty()
    )

    /*if (!this.data.breadLoaded) {
      app.showLoading()
    }*/

  },
  breadListCallBack: function (res) {
    //app.hideLoading()
    this.hideLoading()

    res = res.data
    if (!res || !res.products || res.products.length === 0) {
      this.dealEmpty()
      return
    }

    var products = res.products
    var breadlist = []

    if (this.idFlag) {
      app.globalData.idFlag = null
    } else {
      if (this.data.breadlist.length !== products.length) {
        this.data.scrolltop = 0
      }
    }

    for (var i = 0; i < products.length; i++) {
      var breadinfo = {}
      breadinfo.goodsid = products[i].ID
      breadinfo.name = products[i].NAME
      if (products[i].fname != null && products[i].fname !== undefined) {
        breadinfo.specs = products[i].fname.split(',')
      }
      else {
        breadinfo.specs = []
      }
      if (products[i].fid != null && products[i].fid !== undefined) {
        breadinfo.fid = products[i].fid
      }
      else {
        breadinfo.fid = ''
      }
      breadinfo.img = products[i].PICTURE
      breadinfo.price = +products[i].PRICE
      breadinfo.intro = products[i].SELLINGPOINT
      breadinfo.mealid = products[i].MEALID
      breadinfo.stationId = products[i].stationId
      breadinfo.count = car.checkGoodsCount(breadinfo.mealid)
      breadinfo.contents = products[i].CONTENT.split('@')
      breadinfo.overlay = '0'
      breadinfo.STOCK = products[i].STOCK.stationStockStatus
      breadlist.push(breadinfo)
    }

    this.setData({
      canDisp: res.canDisp,
      idflag: this.idFlag,
      stationId: res.stationId || '',
      storeId: res.storeId || '',
      breadlist: breadlist,
      breadLoaded: true
    })

    allBread = breadlist
    var cgritems = res.flavorList || []
    cgritems.unshift({name: '全部', id: '0'})
    category.init(this, cgritems, this.categoryChooseCallBack)
  },
  hideLoading: function () {
    this.selectComponent('#spin').hide()
  },
  handleCount: function (e) {
    var options = e.currentTarget.dataset.options
    if (options === '1') {
      if (!this.data.canDisp) {
        app.confirm('您的地址不在配送范围内，请修改您的默认地址！', '去修改', '取消').then(confirm => {
          if (confirm) {
            wx.navigateTo({
              url: '/pages/my/address/address?type=select'
            })
          }
        })
        return
      }
    }

    var goodsid = e.currentTarget.dataset.goodsid
    var breadlist = this.data.breadlist

    for (var i = 0; i < breadlist.length; i++) {
      if (breadlist[i].goodsid === goodsid) {
        var count = parseInt(breadlist[i].count)
        count += options * 1
        count = count < 0 ? 0 : count
        count = count > 9999 ? 9999 : count
        breadlist[i].count = count
        break
      }
    }

    this.setData({breadlist: breadlist})
    car.handleCount(e)
  },
  addressHandle: function () {
    if (this.data.goodslist.length > 0) {
      app.confirm('切换地址可能导致购物车中部分商品无效，是否继续？', '是', '否').then(confirm => {
        if (confirm) {
          wx.navigateTo({
            url: '/pages/my/address/address?type=select'
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '/pages/my/address/address?type=select'
      })
    }
  },
  categoryChooseCallBack: function (category_code) {
    if (category_code.id === '0') {
      this.setData({
        breadlist: allBread
      })
    } else {
      var breadlist = []
      for (var i = 0; i < allBread.length; i++) {
        var fidArr = allBread[i].fid.split(',')
        if (fidArr.indexOf(category_code.id.toString()) >= 0) {
          breadlist.push(allBread[i])
        }
      }
      for (var i = 0; i < allBread.length; i++) {
        if (breadlist.indexOf(allBread[i]) < 0) {
          breadlist.push(allBread[i])
        }
      }
      this.setData({
        scrolltop: 0,
        breadlist: breadlist
      })
    }
    category.close()
  },
  goodsScroll: function (e) {
    var topNeedShow = true
    var dateTabFixed
    if (e.detail.deltaY < 0) {
      if (e.detail.scrollTop > 20) {
        topNeedShow = false
      }
      if (e.detail.scrollTop >= tabsTop) {
        dateTabFixed = true
        topNeedShow = true
      }
    } else {
      if (e.detail.scrollTop < tabsTop) {
        dateTabFixed = false
      }
    }
    if (this.data.cgr_show === true) {
      topNeedShow = true
    }
    if (this.data.topNeedShow !== topNeedShow) {
      this.setData({
        topNeedShow: topNeedShow,
      })
    }
    if (dateTabFixed !== undefined && this.data.dateTabFixed !== dateTabFixed) {
      this.setData({
        dateTabFixed: dateTabFixed,
      })
    }
  },

  showCar: car.showCar,
  submitOrder: car.submitOrder,
  closeCar: car.closeCar,
  toggleCar: car.toggleCar,

  showCategory: category.show,
  closeCategory: category.close,
  toggleCategory: category.toggle,
  chooseCategory: category.choose,

  toPageTop: function () {
    this.setData({
      scrolltop: 0
    })
  },
  dealGoodsOverlay: function (e) {
    this.setData({
      showOverlay: false
    })
    var itemindex = Number(e.currentTarget.dataset.itemindex)
    var bread = this.data.breadlist
    bread[itemindex].overlay = '1'
    for (var i = 0; i < bread.length; i++) {
      if (i !== itemindex) {
        bread[i].overlay = '0'
      }
    }
    this.setData({
      breadlist: bread
    })

    this.setData({
      showOverlay: true
    })
  },
  closeAllOverlay: function () {
    var bread = this.data.breadlist
    for (var i = 0; i < bread.length; i++) {
      bread[i].overlay = '0'
    }

    this.setData({
      showOverlay: false
    })

    setTimeout(() => {
      this.setData({
        breadlist: bread
      })
    }, 300)
  },
  initBanner: function () {
    var needCreated = false
    var lastTime = wx.getStorageSync('__timestamp.bkbanner')
    if (!lastTime) {
      needCreated = true
    } else if (new Date().getDate() !== new Date(lastTime).getDate()) {
      needCreated = true
    }
    if (needCreated) {
      setTimeout(() => {
        this.showSlogan()
      }, 1000)
      wx.setStorageSync('__timestamp.bkbanner', Date.now())
    }
  },
  showSlogan: function () {
    this.setData({
      isSloganShow: true
    })
  },
  hideSlogan: function () {
    this.setData({
      isSloganShow: false
    })
  }
})
